package com.opgea.token.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstractDAO<T> {

    @Autowired
    private SessionFactory sessionFactory;

    private Class<T> entityClass;

    public AbstractDAO() {
    }

    public AbstractDAO(Class<T> entityClass) {
	this.entityClass = entityClass;
    }

    public T create(T entity) {
	sessionFactory.getCurrentSession().save(entity);
	return entity;
    }

    public T update(T entity) {
	sessionFactory.getCurrentSession().merge(entity);
	return entity;
    }

    public T delete(T entity) {
	sessionFactory.getCurrentSession().delete(entity);
	return entity;
    }

    @SuppressWarnings("unchecked")
    public T find(Long id) {
	List<T> objects = sessionFactory.getCurrentSession()
		.createCriteria(entityClass).add(Restrictions.eq("id", id))
		.list();
	return objects.get(0);
	// return (T) sessionFactory.getCurrentSession().get(entityClass, id);
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
	Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
		entityClass);
	List<T> objects = criteria.list();
	return objects;
    }

}
